﻿using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AntdUI;

namespace TPressure
{
    public partial class FormPointManageForm : BaseForm
    {
        #region 属性
        /// <summary>设备
        /// 
        /// </summary>
        private FormPoint obj;

        /// <summary>设备点位
        /// 
        /// </summary>
        public DevicePointItem devicePointitem;

        #endregion

        #region 自定义方法

        /// <summary>界面点位列表
        /// 
        /// </summary>
        public void LoadFormPointList()
        {
            List<FormPoint> list = SqlSugarHelper.Inquireable<FormPoint>(null);
            UpdateTable(list);
        }

        /// <summary>更新DataGridView
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateTable(List<FormPoint> list)
        {
            var antItemList = new List<FormPointItem>();
            foreach (FormPoint item in list)
            {
                antItemList.Add(new FormPointItem(item.form_point_number, item.form_point_name, item.device_point_number, item.device_point_name));
            }
            Table1.DataSource = antItemList;
        }

        /// <summary>更新模型
        /// 
        /// </summary>
        private void UpdateObject()
        {
            if (obj == null)
            {
                obj = new FormPoint();
            }
            obj.form_point_number = FormPointNumberInput.Text.ObjToInt();
            obj.form_point_name = FormPointNameInput.Text;
            obj.device_point_number = devicePointitem.point_number;
            obj.device_point_name = DevicePointNameInput.Text;
        }

        /// <summary>刷新
        /// 
        /// </summary>
        private void Reload()
        {
            obj = new FormPoint();
            devicePointitem = null;
            FormPointNumberInput.Text = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            FormPointNameInput.Text = "";
            DevicePointNameInput.Text = "";
        }

        /// <summary>重复检测
        /// 
        /// </summary>
        /// <returns></returns>
        private bool CheckRepeat()
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["form_point_name"] = FormPointNameInput.Text;
            List<FormPoint> list = SqlSugarHelper.Inquireable<FormPoint>(where);
            int count = list.Count;
            if (count > 0)
            {
                AntdUI.Message.error(this, where["form_point_name"] + "已存在", Font);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>根据编号查询记录
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private FormPoint FormPointWithNumber(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["form_point_number"] = number;
            List<FormPoint> list = SqlSugarHelper.Inquireable<FormPoint>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>判断记录是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckSelectedRowExist(int number)
        {
            obj = FormPointWithNumber(number);
            if (obj == null)
            {
                Alert.Error("界面点位记录不存在", this);
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>根据编号查询记录
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private DevicePoint DevicePointWithNumber(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["point_number"] = number;
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        private DevicePointItem DevicePointItem(DevicePoint item)
        {
            string range = item.range_min.ToString() + "-" + item.range_max.ToString();
            string outValue = item.out_min.ToString() + "-" + item.out_max.ToString();
            string alarm = item.alarm_hight.ToString() + "-" + item.alarm_low.ToString();
            string register_type = intToRegister(item.register_type);
            return new DevicePointItem(item.device_number, item.device_name, item.point_number, item.point_name, item.point_address, range, outValue, item.amend, alarm, item.error_range, item.unit, register_type);
        }

        private string intToRegister(int type)
        {
            string registerType = "";
            if (type == 1)
            {
                registerType = "DI";
            }
            else if (type == 2)
            {
                registerType = "DO";
            }
            else if (type == 3)
            {
                registerType = "InputRegister";
            }
            else if (type == 4)
            {
                registerType = "HoldingRegister";
            }
            return registerType;
        }

        /// <summary>刷新设备点位信息
        /// 
        /// </summary>
        public void freshDevicePointInfo()
        { 
            DevicePointNameInput.Text = devicePointitem.point_name;
        }

        #endregion
        #region 系统方法
        public FormPointManageForm()
        {
            InitializeComponent();
        }

        private void FormPointManageForm_Load(object sender, EventArgs e)
        {
            Reload();
            Table1.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("form_point_number","界面点位编号"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("form_point_name","界面点位名称"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("device_point_number","设备点位编号"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("device_point_name","设备点位名称"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("operation","操作"){ Fixed=true,Width="auto",ColAlign=AntdUI.ColumnAlign.Center}
            };
            Spin.Config config = new Spin.Config
            {
                Text = "正在加载中...",
            };
            Table1.Spin(config, () =>
            {
                LoadFormPointList();
            }, () =>
            {

            });
        }
        #endregion

        #region 按钮点击
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            if (obj.form_point_number > 0) 
            {
                if (FormPointNameInput.Text != obj.form_point_name)
                {
                    bool repeatRes = CheckRepeat();
                    if (repeatRes)
                    {
                        return;
                    }
                }

                if (FormPointNameInput.Text.Length == 0)
                {
                    Alert.Error("请输入界面点位名称", this);
                    FormPointNameInput.Focus();
                    return;
                }

                if (devicePointitem == null)
                {
                    Alert.Error("请选择设备点位", this);
                    return;
                }

                UpdateObject();
                List<FormPoint> list = new List<FormPoint>();
                list.Add(obj);
                int res = SqlSugarHelper.Updateable<FormPoint>(list);
                if (res > 0)
                {
                    RefreshButton_Click(this.RefreshButton, null);
                }
                else
                {
                    Alert.Error("编辑界面点位失败", this);
                }
            }
            else
            {
                if (FormPointNameInput.Text.Length == 0)
                {
                    Alert.Error("请输入界面点位名称", this);
                    FormPointNameInput.Focus();
                    return;
                }

                if (devicePointitem == null)
                {
                    Alert.Error("请选择设备点位", this);
                    return;
                }

                bool repeatRes = CheckRepeat();
                if (repeatRes)
                {
                    return;
                }
                UpdateObject();
                List<FormPoint> list = new List<FormPoint>();
                list.Add(obj);
                int res = SqlSugarHelper.Insertable(list);
                if (res > 0)
                {
                    RefreshButton_Click(this.RefreshButton, null);
                }
                else
                {
                    Alert.Error("添加界面点位失败", this);
                }
            }
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            Reload();
            Task.Run(() =>
            {
                LoadFormPointList();
            });
        }

        private void DevicePointNameInput_Click(object sender, EventArgs e)
        {
            SelectDevicePointForm frm = new SelectDevicePointForm();
            frm.Owner = this;
            frm.ShowDialog();
        }
        #endregion

        private void Table1_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is FormPointItem data)
            {

                AntdUI.CellLink link = e.Btn;
                if (link.Id == "edit")
                {
                    bool res = CheckSelectedRowExist(data.form_point_number) ;
                    if (!res)
                    {
                        return;
                    }
                    DevicePoint point = DevicePointWithNumber(data.device_point_number);
                    if (point != null)
                    {
                        devicePointitem = DevicePointItem(point);
                        DevicePointNameInput.Text = data.device_point_name;
                    }
                    FormPointNumberInput.Text = data.form_point_number.ToString();
                    FormPointNameInput.Text = data.form_point_name;
                    
                }
                else if (link.Id == "delete")
                {
                    
                    AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", "您确定要删除此工程吗？")
                    {
                        OnOk = config =>
                        {
                            bool res = CheckSelectedRowExist(data.form_point_number);
                            if (!res)
                            {
                                return true;
                            }
                            List<FormPoint> list = new List<FormPoint>();
                            list.Add(obj);
                            int deleteRes = SqlSugarHelper.Deleteable(list);
                            if (deleteRes > 0)
                            {
                                LoadFormPointList();
                            }
                            else
                            {
                                Alert.Error("删除界面点位失败", this);
                            }
                            return true;
                        },
                    });
                }
            }
        }
    }
}
